package com.kk.travel.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ValidateCodeServlet extends HttpServlet {
	public static final String CHECK_CODE_KEY = "CHECK_CODE_KEY";
	
	//设置验证图片的宽度, 高度, 验证码的个数
	private int width = 100;
	private int height = 60;
	private int codeCount = 4;
	

	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
	    BufferedImage bufferedImage=new BufferedImage(100, 25, BufferedImage.TYPE_INT_RGB);
	    //画验证码
	    Graphics g = bufferedImage.getGraphics();
	    //背景颜色
	    g.setColor(Color.WHITE);
	    //画边框
	    g.fillRect(0, 0, width, height);
	    //字符串流
	    StringBuffer stringBuffer=new StringBuffer();
	    Random random=new Random();
	    //可选择的字符
	    char[] ch="abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); 
	    Font font2 = new Font("宋体", Font.BOLD, 20);
	    g.setFont(font2);
	    
		//随机产生 15 条干扰线, 使图像中的认证码不易被其它程序探测到
		g.setColor(Color.GREEN);
		for(int i = 0; i < 55; i++){
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(20);
			int y1 = random.nextInt(20);
			g.drawLine(x, y, x + x1, y + y1);
		}
	    
	    for(int i=0;i<codeCount;i++){
	      //随机产生的数
	      int index=random.nextInt(ch.length);
	      //随机产生的颜色
	      g.setColor(new Color(random.nextInt(88),random.nextInt(188),random.nextInt(255)));
	      //产生数字的间隔
	      g.drawString(ch[index]+"", i*20+20, 15);
	      
	      //将产生的数字或字符拼接
	      stringBuffer.append(ch[index]+"");
	    }
	    //把字符串保存在session中
	    req.getSession().setAttribute("CHECK_CODE_KEY", stringBuffer.toString().toLowerCase());
	    resp.setContentType("text/html;charset=UTF-8");
		//禁止图像缓存
		resp.setHeader("Pragma", "no-cache");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setDateHeader("Expires", 0);
		
		
		//将图像输出到输出流中
		ServletOutputStream sos = null;
		sos = resp.getOutputStream();
		ImageIO.write(bufferedImage, "jpeg", sos); 
		sos.close();

	}
       
    
}
